package com.mapbased.util;

import java.io.BufferedReader;
import java.io.IOException;

public class Streaming
{
    public Streaming()
    {
        super();
    }

    /**
     * default max=650k
     * default charset=gbk;
     * @param is InputStream
     * @return String
     * @throws IOException
     */
    public static final String readStrFromStream(java.io.InputStream is)
        throws IOException
    {
        return readStrFromStream(is,650000,"gbk");
    }

    /**
     * default 650k
     * @param is InputStream
     * @return byte[]
     */
    public static final byte[] readBytesFromStream(java.io.InputStream is)
        throws IOException
    {
        return readBytesFromStream(is,650000);
    }

    public static final String readStrFromStream(java.io.InputStream is,int max,
                                                 String encode)
        throws IOException
    {
        try
        {
            BufferedReader r=new
                java.io.BufferedReader(
                    new java.io.InputStreamReader(is,encode));

            StringBuilder sb=new StringBuilder();

            while(true)
            {
                String s=r.readLine();

                if(s == null)
                {
                    break;
                }
                else
                {
                    sb.append(s).append("\n");
                    if(sb.length() > max)
                    {
                        break;
                    }
                }

            }
            return sb.toString();
        }
        finally
        {
            if(is != null)
            {
                is.close();

            }

        }

    }

    public static final byte[] readBytesFromStream(java.io.InputStream is,
        int max)
        throws IOException
    {
        try
        {
            java.io.BufferedInputStream bis=new java.io.BufferedInputStream(is);

            java.io.ByteArrayOutputStream bos=new java.io.ByteArrayOutputStream();

            while(true)
            {
                int b=bis.read();

                if(b < 0)
                {
                    break;
                }
                else
                {
                    bos.write(b);
                    if(bos.size() > max)
                    {
                        break;
                    }
                }
            }
            return bos.toByteArray();
        }
        finally
        {
            if(is != null)
            {
                is.close();

            }

        }

    }

}
